// client.cpp
#include "common.hpp"
#include <thread>

class ChatClient {
public:
    ChatClient(std::string ip, int port) : ip_(ip), port_(port) {}

    // void run() {
    //     sock_ = socket(AF_INET, SOCK_STREAM, 0);
    //     if (sock_ == -1) { perror("socket"); exit(1); }

    //     sockaddr_in addr{};
    //     addr.sin_family = AF_INET;
    //     addr.sin_port = htons(port_);
    //     if (inet_pton(AF_INET, ip_.c_str(), &addr.sin_addr) <= 0) {
    //         perror("inet_pton"); exit(1);
    //     }

    //     if (connect(sock_, (sockaddr*)&addr, sizeof(addr)) == -1) {
    //         perror("connect"); exit(1);
    //     }
    //     std::cout << "Connected to server " << ip_ << ":" << port_ << "\n";

    //     std::thread recv_thr(&ChatClient::recvLoop, this);

    //     std::string line;
    //     while (std::getline(std::cin, line)) {
    //         if (line == "/quit") break;
    //         send(sock_, line.c_str(), line.size(), 0);
    //     }

    //     close(sock_);
    //     recv_thr.join();
    // }

 void run() 
 {
        sock_ = socket(AF_INET, SOCK_STREAM, 0);
        sockaddr_in addr{};
        addr.sin_family = AF_INET;
        addr.sin_port = htons(8080);
        inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
        connect(sock_, (sockaddr*)&addr, sizeof(addr));

        std::cout << "[Client] Connected. Type /quit to exit\n";

        // 1. 开启接收线程
        std::thread recv_thr(&ChatClient::recvLoop, this);

        // 2. 主循环：立即把键盘数据发出去
        std::string line;
        while (std::getline(std::cin, line)) {
            if (line == "/quit") break;
            send(sock_, line.c_str(), line.size(), 0);
        }
        close(sock_);
        recv_thr.join();
    }


private:
    std::string ip_;
    int port_;
    int sock_;

    // void recvLoop() {
    //     char buf[BUF_SIZE];
    //     while (true) {
    //         ssize_t bytes = recv(sock_, buf, BUF_SIZE - 1, 0);
    //         if (bytes <= 0) break;
    //         buf[bytes] = '\0';
    //         std::cout << buf << '\n';
    //     }
    // }


     void recvLoop() {
        char buf[BUF_SIZE];
        while (true) {
            ssize_t n = recv(sock_, buf, BUF_SIZE - 1, 0);
            if (n <= 0) break;
            buf[n] = '\0';
            std::cout << "[Client] Server echo: " << buf << '\n';
        }
    }
};

int main(int argc, char* argv[]) {
    if (argc != 3) {
        std::cerr << "Usage: ./client <server_ip> <port>\n";
        return 1;
    }
    ChatClient client(argv[1], std::stoi(argv[2]));
    client.run();
    return 0;
}